package example;

import framework.BoardInterface;
import framework.CellInterface;

/**
 * This is a sample automaton plugin that follows the rules of Conway's Game of
 * Life.
 * 
 */
public class SampleAutomatonPlugin implements
		framework.AutomatonPluginInterface {

	private BoardInterface board;

	/**
	 * Constructor that initializes the board field
	 * 
	 * @param BoardInterface b - a board containing all the cells
	 */
	public SampleAutomatonPlugin(BoardInterface b) {
		this.board = b;
	}

	
	/**
	 * This method returns the current board. Board object is initialized by
	 * client. Note that when initializing the board, the client must initialize
	 * each cell. This includes setting the initial state of each cell using
	 * method setState(state) and the x and y coordinates of position of
	 * each cell using setRowNum(r) and setColNum(c).
	 * 
	 * @return BoardInterface board - the board containing all the cells
	 */
	@Override
	public BoardInterface getBoard() {
		return board;
	}

	
	/**
	 * Given a cell and its neighbors, this method updates the cell's state by
	 * looking at the states of neighbor cells and following some client-defined
	 * rule. Note that states are implemented as int. This sample uses the rules 
	 * from Conway's Game of Life
	 * 
	 * @param CellInterface c - a cell that need to be updated
	 * @param int[] NbrStates - the states of the cell's neighbors
	 */
	@Override
	public void updateCellState(CellInterface c, int[] NbrStates) {
		int stateSum = 0;
		// This sample looks at 8 surrounding neighbors of the cell
		for (int i = 0; i < board.getNbrNum(); i++) {
			stateSum += NbrStates[i];
		}
		if (c.getState() == 1 && stateSum < 2) {
			c.setState(0);
		} else if (c.getState() == 1 && (stateSum == 2 || stateSum == 3)) {
			c.setState(1);
		} else if (c.getState() == 1 && stateSum > 3) {
			c.setState(0);
		} else if (c.getState() == 0 && stateSum == 3) {
			c.setState(1);
		} else {
			c.setState(0);
		}
	}

	
	/**
	 * Returns an array of all cell states.
	 * 
	 * @return int[] states - all the possible states of the cells
	 */
	@Override
	public int[] getAllStates() {
		// This sample has 2 states, 0 for dead state, 1 for live state
		int[] states = { 0, 1 };
		return states;
	}
}
